package com.ws.wsdemo2.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ws.wsdemo2.model.QuotePeriod;
import com.ws.wsdemo2.service.IComputeService;
import com.ws.wsdemo2.util.QuotePeriodUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @Classname ComputeServiceImpl
 * @Description TODO
 * @Date 2019/5/20 11:19
 * @Created by Administrator
 */
@Service
public class ComputeServiceImpl implements IComputeService {
    @Autowired
    QuotePeriodUtil quotePeriodUtil;
    @Override
    public void statistical(Jedis jedis, int count, QuotePeriodUtil.PeriodType periodType, JSONObject marketData) {

        boolean flag=true;
        // 获取当前行情归属那个时间周期
        long timestamp = marketData.getLong("DEALTIME");
        String exchangeTag = marketData.getString("EXCHANGE_TAG");
        String symbol = marketData.getString("SYMBOL");// 行情商品
        QuotePeriod quotePeriod = quotePeriodUtil.getPeriod(exchangeTag, periodType, new Date(timestamp * 1000), symbol);
        if (quotePeriod == null) {
            return;
        }
        String qkey="QUOTESERVICE:%s_MARKET_DATA:%s";
        BigDecimal last = marketData.getBigDecimal("LAST");// 最新价格
        String key = String.format(qkey,periodType.name(),1097);
        while(flag){
            jedis.watch(key);//监听key（一旦有其他人操作该key，则下面逻辑会执行失败。）
            String score = String.valueOf(quotePeriod.getStartTime() / 1000);//以时间戳为分数
            Set<String> memberSet = jedis.zrangeByScore(key, score, score);
            JSONObject memberData = new JSONObject();
            if(memberSet==null||StringUtils.isEmpty(memberSet)||memberSet.size()==0){//不存在此k线数据，则说明是新的k线
                //开始价格
                memberData.put("START",marketData.getString("PRICE"));
                //结束价格
                memberData.put("END",marketData.getString("PRICE"));
                //最新价格
                memberData.put("LAST",marketData.getString("PRICE"));
                //最低价格
                memberData.put("LOW",marketData.getString("PRICE"));
                //最高价格
                memberData.put("HIGH",marketData.getString("PRICE"));
                //成交量
                memberData.put("DEALCOUNT",marketData.getString("DEALCOUNT"));
                //成交额
                memberData.put("DEALAMOUNT",marketData.getString("DEALAMOUNT"));
                //时间
                memberData.put("TIMESATAMP",quotePeriod.getStartTime()/1000);
                jedis.zadd(key,Double.valueOf(score),memberData.toJSONString());//插入k线数据
                flag=false;
            }else{
                JSONObject oldMemberJSON = JSONObject.parseObject(memberSet.iterator().next());
                memberData.put("START",oldMemberJSON.getString("START"));//开始价
                memberData.put("END",marketData.getString("PRICE"));//结束价
                memberData.put("LAST",marketData.getString("PRICE"));//最新价
                memberData.put("LOW",oldMemberJSON.getBigDecimal("LOW").compareTo(marketData.getBigDecimal("PRICE"))<0?oldMemberJSON
                        .getBigDecimal("LOW").toPlainString():marketData.getBigDecimal("PRICE").toPlainString());//最低价
                memberData.put("HIGH",oldMemberJSON.getBigDecimal("HIGH").compareTo(marketData.getBigDecimal("PRICE"))<0?marketData
                        .getBigDecimal("PRICE").toPlainString():oldMemberJSON.getBigDecimal("HIGH").toPlainString());//最高价
                //成交量
                memberData.put("DEALCOUNT",oldMemberJSON.getBigDecimal("DEALCOUNT").add(marketData.getBigDecimal("DEALCOUNT")).toPlainString());
                //成交额=价格*成交量+原始成交量
                memberData.put("DEALAMOUNT",marketData.getBigDecimal("DEALAMOUNT").multiply(marketData.getBigDecimal("DEALAMOUNT"))
                        .add(oldMemberJSON.getBigDecimal("DEALAMOUNT")).toPlainString());
                memberData.put("TIMESATAMP",quotePeriod.getStartTime()/1000);//时间

                Transaction transaction = jedis.multi();//开启事物
                transaction.zremrangeByScore(key,Double.valueOf(score),Double.valueOf(score));//先移除原先的数据
                transaction.zadd(key,Double.valueOf(score),memberData.toJSONString());//插入k线数据
                List list = transaction.exec();
                if (list!=null){
                    System.out.println("插入成功");
                    flag=false;
                }else {
                    flag=true;
                    System.out.println("插入失败");
                }
               /* jedis.zremrangeByScore(key,Double.valueOf(score),Double.valueOf(score));
                jedis.zadd(key,Double.valueOf(score),memberData.toJSONString());//插入k线数据*/
            }
        }
    }
}
